package com.mobilepay.moneypig.model.activity.launcher;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.igexin.sdk.PushManager;
import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.config.DIR;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.model.dialog.TipDialog;
import com.mobilepay.moneypig.model.fragment.HomePageFragment;
import com.mobilepay.moneypig.model.fragment.PersonFragment;
import com.mobilepay.moneypig.model.service.DlbIntentService;
import com.mobilepay.moneypig.model.service.DlbPushService;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.getui.GetuiData;
import com.mobilepay.moneypig.response.mine.UserDetailData;
import com.mobilepay.moneypig.response.update.AppUpdate;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.LogDebug;
import com.mobilepay.moneypig.utils.NotificationCheckUtil;
import com.mobilepay.moneypig.utils.NotificationUtils;
import com.mobilepay.moneypig.utils.SysUtil;
import com.mobilepay.moneypig.view.NoScrollViewPager;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends BaseActivity {
    private static final String TAG = "MainActivity";
    private TextView mTextViewOne, mTextViewTwo;
    private ImageView mImageViewOne, mImageViewTwo;
    private HomePageFragment mHomeFragment = new HomePageFragment();
    private PersonFragment mPersonFragment = new PersonFragment();
    private static ArrayList<Fragment> mFragmentList;
    private NoScrollViewPager mViewPager;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void initViews() {
        mTextViewOne = (TextView) findViewById(R.id.tab_text_one);
        mTextViewTwo = (TextView) findViewById(R.id.tab_text_two);
        mImageViewOne = (ImageView) findViewById(R.id.tab_image_one);
        mImageViewTwo = (ImageView) findViewById(R.id.tab_image_two);
        mViewPager = (NoScrollViewPager) findViewById(R.id.main_viewpager);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        App.getApp().mainActivity = this;
        mainActivity = this;
        initGetui();
        App.getApp().setNotFirstUse();
        setOneState();
        addFragmentToList();
        fillAdapter();
        showMessageTip();
        checkVersonUpdate();//检测新版本
    }

    /**
     * 判断消息提醒设置是否打开
     */
    private void showMessageTip() {
        //检测通知开关是否开启
        if (!NotificationCheckUtil.notificationIsOpen(mainActivity)) {
            mainActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showConfirm("提示", "    消息提醒已关闭，你将收不到应用通知和活动提醒。是否打开？");
                }
            });
        }
    }

    static int count = 1;
    static MainActivity mainActivity;

    public void sendNotification(String content) {
        getUserDetail();// 收到推送更新用户信息
        new MyThread(content).start();
    }

    private static class MyThread extends Thread {
        private String content;

        MyThread(String content) {
            this.content = content;
        }

        @Override
        public void run() {
            GetuiData data = GsonUtil.GsonToBean(content, GetuiData.class);
            count++;
            //状态栏显示通知内容
            NotificationUtils.createNotif(mainActivity,
                    R.mipmap.pig_icon, "",
                    data.getTitle(),
                    data.getText(),
                    new Intent(mainActivity, MainActivity.class),
                    count,
                    1500);
//            //应用内弹窗提醒
//            if (!CommonUtil.isAppBackground(App.getApp())) {
//                mainActivity.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        showConfirm("消息", "您收到一条推送消息，需要进入设置界面打开推送开关后查看。");
//                    }
//                });
//            }
        }
    }

    private static TipDialog confirmDialog;

    private static void showConfirm(String title, String content) {
        if (confirmDialog == null) {
            confirmDialog = new TipDialog(mainActivity);
        }
        confirmDialog.setTitle(title);
        confirmDialog.setContent(content);
        confirmDialog.setCancelable(true);
        confirmDialog.setConfirm("去设置");
        //设置为系统弹窗，任何位置都可以弹出
//        confirmDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
        confirmDialog.show();
        confirmDialog.setListener(new TipDialog.Listener() {
            @Override
            public void onConfirm() {
                super.onConfirm();
                confirmDialog.dismiss();
                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                mainActivity.startActivity(intent);
            }

            @Override
            public void onDismiss() {
                super.onDismiss();
                confirmDialog.dismiss();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void sendCliendId(String cliend_id) {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.getui_bind);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("client_id", cliend_id);
        param.add("client_type", "ANDROID");
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
//                showToastShort(string);
            }
        });//绑定client id
    }

    private static final int REQUEST_PERMISSION = 0;
    // DemoPushService.class 自定义服务名称, 核心服务
    private Class userPushService = DlbPushService.class;

    private void initGetui() {
        PackageManager pkgManager = getPackageManager();
        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission = pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        // read phone state用于获取 imei 设备信息
        boolean phoneSatePermission = pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission) {
            requestPermission();
        } else {
            PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
        }
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DlbIntentService.class);
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE}, REQUEST_PERMISSION);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION) {
            if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
            } else {
                PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    //add fragment to arraylist
    private void addFragmentToList() {
        mFragmentList = new ArrayList<>();
        mFragmentList.add(mHomeFragment);
        mFragmentList.add(mPersonFragment);
    }

    private void fillAdapter() {
        MyFragmentViewPagerAdapter myFragmentViewPagerAdapter = new MyFragmentViewPagerAdapter(this.getSupportFragmentManager());
        mViewPager.setAdapter(myFragmentViewPagerAdapter);
        mViewPager.setCurrentItem(0);
        mViewPager.setOffscreenPageLimit(2);
        mViewPager.setScroll(false);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        setOneState();
                        break;
                    case 1:
                        setTwoState();
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void onSetListener() {
        findViewById(R.id.tab_one).setOnClickListener(this);
        findViewById(R.id.tab_two).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tab_one:
                setOneState();
                break;
            case R.id.tab_two:
                setTwoState();
                break;
        }
    }

    // tab one
    private void setOneState() {
        mTextViewOne.setSelected(true);
        mTextViewTwo.setSelected(false);
        mImageViewOne.setSelected(true);
        mImageViewTwo.setSelected(false);
        mViewPager.setCurrentItem(0);
    }

    // tab two
    private void setTwoState() {
        mTextViewOne.setSelected(false);
        mTextViewTwo.setSelected(true);
        mImageViewOne.setSelected(false);
        mImageViewTwo.setSelected(true);
        mViewPager.setCurrentItem(1);
    }


    private static class MyFragmentViewPagerAdapter extends FragmentPagerAdapter {

        public MyFragmentViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

    }

    private String mApkUrl;
    private String mUpdateVersion;

    /**
     * 检查版本更新
     */
    public void checkVersonUpdate() {
        final String mCurrentVersion = CommonUtil.getVersionName(App.getApp());
        HttpUtils.RequestParam params = new HttpUtils.RequestParam();
        params.add("method", NetConfig.updateApk);
        params.add("client_version", mCurrentVersion);
        params.add("client_type", "ANDROID");
        params.add("sign", params.getMd5String());
        HttpUtils.getInstance().params(params).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                if (CommonUtil.isForeground(MainActivity.this)) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        AppUpdate appUpdate = GsonUtil.GsonToBean(string, AppUpdate.class);
                        mApkUrl = appUpdate.getData().getAndroid_download();
                        mUpdateVersion = appUpdate.getData().getAndroid_version();
                        //是否更新
                        if (!mCurrentVersion.equals(mUpdateVersion)) {
                            File dir = new File(DIR.TEMP_APK);
                            //删除已存在的apk
                            if (dir.exists()) {
                                File[] files = dir.listFiles();
                                for (File file : files) {
                                    if (file.getName().contains(".apk")) {
                                        try {
                                            CommonUtil.deleteFile(file);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                            foundUpdate();
                        }
                    } else {
                        showToastShort(responseResult.getInfo());
                    }
                }
            }
        });
    }

    private void foundUpdate() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showUpdateTip();
            }
        });
    }

    //下载应用
    private void downLoadApk() {
        HttpUtils.getInstance().loadFile(mApkUrl, new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
            }

            @Override
            public void onResponseProgress(long progress, long total, boolean done) {
                float per = (float) progress / (float) total * (float) 100;
                String pers = String.valueOf(per);
                if (pers.length() > 5) {
                    pers = pers.substring(0, 5);
                }
                final String finalPers = pers;
                showDownProgress("正在下载" + " " + finalPers + "%");
            }

            @Override
            public void onHttpSuccess(byte[] bytes) {
                showDownProgress("准备安装，请稍后");
                String savepath = DIR.TEMP_APK + "/" + mUpdateVersion + ".apk";
                File file = new File(savepath);
                try {
                    CommonUtil.byte2File(bytes, file.getParent(), file.getName());
                    dismissDownProgress();
                    SysUtil.installApk(App.getApp(), file.getPath());
                } catch (Exception e) {
                    LogDebug.e(e);
                }
            }
        });
    }

    private TipDialog mUpdateTip;

    private void showUpdateTip() {
        if (mUpdateTip == null) {
            mUpdateTip = new TipDialog(getThis());
            mUpdateTip.setContent("发现新版，是否更新？");
            mUpdateTip.setCancle("否");
            mUpdateTip.setConfirm("是");
            mUpdateTip.setCancelable(true);
            mUpdateTip.setListener(new TipDialog.Listener() {
                @Override
                public void onConfirm() {
                    downLoadApk();
                }

                @Override
                public void onDismiss() {
                    super.onDismiss();
                    mUpdateTip.dismiss();
                }
            });
        }
        mUpdateTip.show();
    }

    //账户信息
    private void getUserDetail() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.get_detail);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        UserDetailData data = GsonUtil.GsonToBean(string, UserDetailData.class);
                        App.getApp().setUserDetailInfo(data);//保存账户信息
                    }
                }
            }
        });
    }
}

